package com.gitee.zhanyao.codebase.java.weixin.service.impl;

import com.gitee.zhanyao.codebase.java.weixin.constant.UrlConstant;
import com.gitee.zhanyao.codebase.java.weixin.model.WeiXinResponse;
import com.gitee.zhanyao.codebase.java.weixin.model.WeiXinUserlist;
import com.gitee.zhanyao.codebase.java.weixin.properties.WeiXinProperties;
import com.gitee.zhanyao.codebase.java.weixin.service.IWeiXinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author zhanyao
 */
@Service
public class WeiXinServiceImpl implements IWeiXinService {

    @Autowired
    private WeiXinProperties weiXinProperties;

    @Autowired
    private RestTemplateBuilder restTemplateBuilder;

    /**
     * 获取 token
     */
    @Override
    public String getToken() {
        Map<String, Object> params = new HashMap<>();
        params.put("corpid", weiXinProperties.getCorpId());
        params.put("corpsecret", weiXinProperties.getCorpSecret());
        RestTemplate restTemplate = restTemplateBuilder.build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(headers);
        ParameterizedTypeReference<WeiXinResponse> responseType = new ParameterizedTypeReference<WeiXinResponse>() {
        };
        ResponseEntity<WeiXinResponse> responseEntity = restTemplate.exchange(
                weiXinProperties.getServer() + UrlConstant.WEI_XIN_GET_TOKEN,
                HttpMethod.GET, request, responseType, params);
        WeiXinResponse weiXinResponse = responseEntity.getBody();
        return weiXinResponse.getAccessToken();
    }

    @Override
    public List<WeiXinUserlist> getUserList(String accessToken, Integer departmentId, Integer fetchChild) {
        Map<String, Object> params = new HashMap<>();
        params.put("accessToken", accessToken);
        params.put("departmentId", departmentId);
        // 是否递归获取子部门下面的成员
        params.put("fetchChild", fetchChild);
        RestTemplate restTemplate = restTemplateBuilder.build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(headers);
        ParameterizedTypeReference<WeiXinResponse> responseType = new ParameterizedTypeReference<WeiXinResponse>() {
        };
        ResponseEntity<WeiXinResponse> responseEntity = restTemplate.exchange(
                weiXinProperties.getServer() + UrlConstant.WEI_XIN_USER_LIST,
                HttpMethod.GET, request, responseType, params);
        WeiXinResponse weiXinResponse = responseEntity.getBody();
        return weiXinResponse.getUserlist();
    }

    @Override
    public void sendMessage(String template, Map<String, String> templateParams, Set<String> toUsers) throws Exception {
        String message = replaceTemplate(template, templateParams);
        String token = getToken();
        StringBuffer touserSb = new StringBuffer();
        for (String toUser : toUsers) {
            touserSb.append(toUser);
            touserSb.append("|");
        }
        touserSb.deleteCharAt(touserSb.length() - 1);
        Map<String, Object> urlParams = new HashMap<>();
        urlParams.put("accessToken", token);

        Map<String, Object> contentParams = new HashMap<>();
        contentParams.put("content", message);

        Map<String, Object> bodyParams = new HashMap<>();
        bodyParams.put("touser", touserSb.toString());
        bodyParams.put("msgtype", "text");
        bodyParams.put("agentid", weiXinProperties.getAgentId());
        bodyParams.put("text", contentParams);
        bodyParams.put("safe", 0);
        bodyParams.put("enable_id_trans", 0);
        bodyParams.put("enable_duplicate_check", 0);
        bodyParams.put("duplicate_check_interval", 1800);
        RestTemplate restTemplate = restTemplateBuilder.build();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> request = new HttpEntity<>(bodyParams, headers);
        ParameterizedTypeReference<WeiXinResponse> responseType = new ParameterizedTypeReference<WeiXinResponse>() {
        };
        restTemplate.exchange(weiXinProperties.getServer() + UrlConstant.WEI_XIN_MESSAGE_SEND,
                HttpMethod.POST, request, responseType, urlParams);
    }

    private String replaceTemplate(String template, Map<String, String> templateParams) {
        String tmpMessage = template;
        for (Map.Entry<String, String> entry : templateParams.entrySet()) {
            tmpMessage = tmpMessage.replaceAll("\\{\\{" + entry.getKey() + "\\}\\}",
                    StringUtils.hasText(entry.getValue()) ? entry.getValue() : "");
        }
        return tmpMessage;
    }

}
